package com.yc.book.biz;

import com.yc.book.servlet.UploadServlet;
import com.yc.book.util.DBUtil;
import com.yc.book.util.Utils;

import java.io.File;

public class BookBiz {
    public void save(String id,String bookname,String bookpress,String pressdate,String bookauthor,String bookcount,String bookimage){
        //字段验证
        Utils.checkEmpty(bookname,"书名不能为空");
        Utils.checkEmpty(bookpress,"出版社不能为空");
        Utils.checkEmpty(pressdate,"出版时间不能为空");
        Utils.checkEmpty(bookauthor,"作者不能为空");
        Utils.checkEmpty(bookcount,"库存不能为空");
        Utils.checkEmpty(bookimage,"封面不能为空");
        Utils.check(bookauthor.length()<2,"作者名不能少于两个字符");
        Utils.check(!bookcount.matches("\\d+"),"库存必须是数字");
        Utils.check(Integer.parseInt(bookcount) <= 0,"库存必须大于0");


        //同名验证
        String sql = "select * from books where bookname = ?";
        //如果是修改，则排除自己
        if (id != null && !id.isBlank()) {
            sql += " and id != " + id;
        }
        DBUtil db = new DBUtil();
        Utils.check(db.total(sql,bookname) > 0,"书名已存在");

        //保存到数据库
        if (id != null ) {
            //修改图书
            sql = "update books set bookname = ?,bookpress = ?,pressdate = ?,bookauthor = ?,bookcount = ?,bookimage = ? where id = ?";
            db.update(sql,bookname,bookpress,pressdate,bookauthor,bookcount,bookimage,id);
        }else {
            sql = "insert into books values(default,?,?,?,?,?,?)";
            db.update(sql,bookname,bookpress,pressdate,bookauthor,bookcount,bookimage);
        }

    }



    public void delete(String id){
        //字段验证
        Utils.checkEmpty(id,"被删除的图书编号不能为空");
        //数据库完整性校验，例如：已经外借或者预约的图书，不能删除
        //删除图书图片，前提是图片是上传的图片
        DBUtil db = new DBUtil();
        String sql = "select bookimage from books where id = ?";
        String bookimage = db.find(sql,id).get("bookimage");
        String filename = bookimage.substring(bookimage.lastIndexOf("/"));
        UploadServlet uploadServlet = new UploadServlet();
        String filepath =uploadServlet.getUploadDir() + filename;
        File file = new File(filepath);
        if (file.exists()) {
            if (file.delete() == false) {
                System.out.println("删除文件失败:" + filepath);
            }else {
                System.out.println("删除文件成功：" + filepath);
            }
        }

        //删除垃圾数据
        sql = "delete from books where id = ?";
        db.update(sql,id);
    }
}
